package com.chang.order.web;

import com.chang.common.exception.NoStockException;
import com.chang.order.service.OrderService;
import com.chang.order.vo.OrderConfirmVo;
import com.chang.order.vo.OrderSubmitVo;
import com.chang.order.vo.SubmitOrderResponseVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * @author: changzhenxi
 * @date: 2025年01月06日 10:46
 * @Version: 1.0
 * @description:
 */
@Slf4j
@Controller
public class OrderWebController {

    @Resource
    OrderService orderService;

    @GetMapping("toTrade")
    public String toTrade(Model model) {
        // 封装订单确认页需要用到的vo
        OrderConfirmVo confirmOrderData = orderService.confirmOrder();
        model.addAttribute("confirmOrderData", confirmOrderData);
        return "confirm";
    }

    // 下单功能
    @PostMapping("submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, Model model, RedirectAttributes redirectAttributes) {
        log.info("下单接口入参orderSubmitVo:{}", orderSubmitVo);
        try {
            // 下单，创建订单，验证令牌，对比价格，锁库存
            SubmitOrderResponseVo orderResponseVo = orderService.submitOrder(orderSubmitVo);
            log.info("获取订单封装结果orderResponseVo=>{}", orderResponseVo);
            // 下单成功来到支付页

            // 下单成功来到支付选择页面
            if (orderResponseVo.getCode() == 0) {
                model.addAttribute("submitOrderResp", orderResponseVo);
                return "pay";
            } else {
                String msg = "下单失败:";
                log.info("orderResponseVo.getCode()=>{}", orderResponseVo.getCode());
                switch (orderResponseVo.getCode()) {
                    case 1:
                        msg += "订单信息过期,请刷新后再次提交";
                        break;
                    case 2:
                        msg += "订单商品价格发生变化,请确认后再次提交";
                        break;
                    case 3:
                        msg += "库存锁定失败,商品库存不足";
                        break;
                }
                // 下单失败回到订单确认页确认订单信息
                redirectAttributes.addFlashAttribute("msg", msg);
                return "redirect:http://order.gulimall.com/toTrade";
            }
        } catch (Exception e) {
            if (e instanceof NoStockException) {
                String message = e.getMessage();
                redirectAttributes.addFlashAttribute("msg", message);
            }
            return "redirect:http://order.gulimall.com/toTrade";
        }

    }
}
